import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import axios from 'axios'

// 配置axios基础URL - 从环境变量获取
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:5000/api'

// 创建专门的axios实例用于认证
const authClient = axios.create({
  baseURL: API_BASE_URL,
  headers: {
    'Content-Type': 'application/json',
  },
  timeout: 10000,
})

export interface User {
  id: number
  username: string
  email: string
  role: string
  name: string
  area_id?: number
  area_name?: string
  areas?: string[]
  area_ids?: number[]
}

export const useAuthStore = defineStore('auth', () => {
  const token = ref<string | null>(localStorage.getItem('token'))

  // 初始化用户信息
  const savedUser = localStorage.getItem('user')
  const user = ref<User | null>(savedUser ? JSON.parse(savedUser) : null)

  // 计算属性
  const isLoggedIn = computed(() => !!token.value)
  const isAdmin = computed(() => user.value?.role === 'admin')
  const isManager = computed(() => user.value?.role === 'manager')

  // 设置认证头
  const setAuthHeader = (authToken: string) => {
    authClient.defaults.headers.common['Authorization'] = `Bearer ${authToken}`
  }

  // 清除认证头
  const clearAuthHeader = () => {
    delete authClient.defaults.headers.common['Authorization']
  }

  // 登录
  const login = async (username: string, password: string) => {
    try {
      const response = await authClient.post('/auth/login', {
        username,
        password
      })

      const { access_token, user: userData } = response.data
      
      token.value = access_token
      user.value = userData

      localStorage.setItem('token', access_token)
      localStorage.setItem('user', JSON.stringify(userData))
      setAuthHeader(access_token)
      
      return userData
    } catch (error: any) {
      throw new Error(error.response?.data?.message || '登录失败')
    }
  }

  // 登出
  const logout = () => {
    token.value = null
    user.value = null
    localStorage.removeItem('token')
    localStorage.removeItem('user')
    clearAuthHeader()
  }

  // 初始化用户信息
  const initUser = async () => {
    if (!token.value) return

    try {
      setAuthHeader(token.value)
      const response = await authClient.get('/auth/me')
      user.value = response.data
      localStorage.setItem('user', JSON.stringify(response.data))
    } catch (error) {
      // 如果获取用户信息失败，清除token
      logout()
      throw error
    }
  }

  // 注册
  const register = async (userData: {
    username: string
    email: string
    password: string
    name: string
    role?: string
  }) => {
    try {
      const response = await authClient.post('/auth/register', userData)
      return response.data
    } catch (error: any) {
      throw new Error(error.response?.data?.message || '注册失败')
    }
  }

  // 更新用户信息
  const updateProfile = async (profileData: Partial<User>) => {
    try {
      const response = await authClient.post('/auth/profile', profileData)
      user.value = { ...user.value, ...response.data }
      localStorage.setItem('user', JSON.stringify(user.value))
      return response.data
    } catch (error: any) {
      throw new Error(error.response?.data?.message || '更新失败')
    }
  }

  // 修改密码
  const changePassword = async (oldPassword: string, newPassword: string) => {
    try {
      await authClient.post('/auth/change-password', {
        old_password: oldPassword,
        new_password: newPassword
      })
    } catch (error: any) {
      throw new Error(error.response?.data?.message || '密码修改失败')
    }
  }

  // 初始化时设置认证头
  if (token.value) {
    setAuthHeader(token.value)
  }

  // 监听token变化，自动设置或清除认证头
  const updateAuthHeader = () => {
    if (token.value) {
      setAuthHeader(token.value)
    } else {
      clearAuthHeader()
    }
  }

  // 在token变化时更新认证头
  updateAuthHeader()

  return {
    token,
    user,
    isLoggedIn,
    isAdmin,
    isManager,
    login,
    logout,
    initUser,
    register,
    updateProfile,
    changePassword
  }
})
